import React, { useState, useEffect, useRef } from 'react';
import { NavBar, Image, Toast, Button, Form, Input, Picker, ImageViewer } from 'antd-mobile';
import { Select } from 'antd';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { ClockCircleOutline } from 'antd-mobile-icons';
import styles from './index.module.css';
import youxiu from '../../../image/youxiu.png';
import liangh from '../../../image/linaghao.png';
import jige from '../../../image/jige.png';
import bujige from '../../../image/bujige.png';
import padd from '../../../image/padding.png';
import request from '../../../axios';

interface DishItem {
  id: string | number;
  dishId?: string | number;
  dishName: string;
  dishPicture: string;
  tags: string;
  storeName: string;
  recordTime: string;
  aiEvaluate: number;
  personEvaluate: number;
  dishTemperature: number;
  aiConfidenceScore?: number;
  aiPredictedDishId?: string | number;
}

// 评分选项
const scoreOptions = [
  [
    { label: "优秀", value: "4" },
    { label: "良好", value: "3" },
    { label: "及格", value: "2" },
    { label: "不及格", value: "1" },
    { label: "待评估", value: "0" },
  ],
];

const DishViewer: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const containerRef = useRef<HTMLDivElement>(null);
  
  const [dishList, setDishList] = useState<DishItem[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const [aiPredictedDishName, setAiPredictedDishName] = useState<string>('');
  const [cookList, setCookList] = useState<any[]>([]);
  const [selectedDishId, setSelectedDishId] = useState<string | number | null>(null);
  const [showImageViewer, setShowImageViewer] = useState(false);
  const [showHistoryTags, setShowHistoryTags] = useState(false);
  const [historyTags, setHistoryTags] = useState<string[]>([]);
  const [form] = Form.useForm();
  const userSelectedDish = useRef(false); // 记录用户是否手动选择过菜品
  
  // 触摸相关状态
  const [touchStart, setTouchStart] = useState({ x: 0, y: 0 });
  const [touchEnd, setTouchEnd] = useState({ x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);
  const [dragOffset, setDragOffset] = useState(0);

  const typeEnum: any = {
    "0": "待评估",
    "1": "不及格", 
    "2": "及格",
    "3": "良好",
    "4": "优秀",
  };

  const aiTypeEnum: any = {
    "0": "待识别",
    "1": "不及格",
    "2": "及格", 
    "3": "良好",
    "4": "优秀",
  };

  // 获取AI评分的优先值：优先使用 aiScorePrediction，fallback到 aiEvaluate
  const getAiScore = (item: any) => {
    return item?.aiScorePrediction !== undefined && item?.aiScorePrediction !== null 
      ? item.aiScorePrediction 
      : item?.aiEvaluate;
  };

  // 获取菜品名称的优先值：优先使用 actualDishName，fallback到 actualAiPredictedDishName
  const getDishName = (item: any) => {
    return item?.actualDishName || item?.actualAiPredictedDishName;
  };

  // 判断是否有有效的菜品名称
  const hasValidDishName = (item: any) => {
    return !!(item?.actualDishName || item?.actualAiPredictedDishName);
  };

  // 判断是否应该显示AI评价：有菜品名称 且 AI评分不为0（待评估）
  const shouldShowAiEvaluation = (item: any) => {
    const hasName = hasValidDishName(item);
    const aiScore = getAiScore(item);
    return hasName && aiScore > 0;
  };

  const getEvaluateImage = (evaluate: number) => {
    switch (evaluate) {
      case 4: return youxiu;
      case 3: return liangh;
      case 2: return jige;
      case 1: return bujige;
      default: return padd;
    }
  };

  const getEvaluateStyle = (evaluate: number) => {
    switch (evaluate) {
      case 4: return 'bingo';
      case 3:
      case 2: return 'good';
      case 1: return 'fail';
      default: return 'padd';
    }
  };

  // 获取AI识别的菜品名称
  const getAiPredictedDishName = async (aiPredictedDishId: string | number) => {
    try {
      const { data } = await request.get('/dish/list/all', {
        id: aiPredictedDishId
      });
      if (data && data.length > 0) {
        return data[0].name || data[0].dishName || '';
      }
    } catch (error) {
      console.error('获取AI识别菜品名称失败:', error);
    }
    return '';
  };

  // 获取菜品列表供编辑使用
  const getCookList = async () => {
    try {
      const { data } = await request.get('/dish/list', {
        pageNo: 1,
        pageSize: 999,
      });
      if (data) {
        setCookList(data?.records || []);
      }
    } catch (error) {
      console.error('获取菜品列表失败:', error);
    }
  };

  // 获取历史标签
  const getHistoryTags = async () => {
    try {
      const dishId = selectedDishId || dishList[currentIndex]?.id;
      if (!dishId) {
        Toast.show("请选择菜品");
        return;
      }
      const { data } = await request.get(`/dish_tag/${dishId}`);
      if (data) {
        setHistoryTags(data);
        setShowHistoryTags(true);
      }
    } catch (error) {
      console.error('获取历史标签失败:', error);
    }
  };

  // 添加历史标签到输入框
  const addHistoryTag = (tag: string) => {
    const currentTags = dishList[currentIndex]?.tags || '';
    const newTags = currentTags + (currentTags ? '#' : '') + tag;
    
    // 更新状态
    const updatedDishList = [...dishList];
    updatedDishList[currentIndex] = {
      ...updatedDishList[currentIndex],
      tags: newTags,
    };
    setDishList(updatedDishList);
    
    // 同步更新表单
    form.setFieldValue("tags", newTags);
    setShowHistoryTags(false);
  };

  // 处理手动保存
  const handleManualSave = async () => {
    try {
      const currentDish = dishList[currentIndex];
      console.log('手动保存 - 当前菜品:', currentDish);
      console.log('手动保存 - 选中的菜品ID:', selectedDishId);
      
      const submitDishId = selectedDishId || currentDish?.dishId || currentDish?.id;
      const selectedDishInfo = cookList.find((item) => item.id === submitDishId);
      
      const submitData = {
        id: currentDish?.id,
        dishId: submitDishId,
        dishName: selectedDishInfo?.name || selectedDishInfo?.dishName || currentDish?.dishName,
        personEvaluate: currentDish.personEvaluate || 0,
        tags: currentDish.tags || '',
        wendu: currentDish.dishTemperature || '',
        scorePerson: '', // 添加这个字段，如果需要的话
      };
      
      console.log('手动保存 - 提交数据:', submitData);
      
      await request.post('/meal_record/score', submitData);
      Toast.show('保存成功');
    } catch (error) {
      console.error('保存失败:', error);
      Toast.show('保存失败');
    }
  };


  // 初始化数据
  useEffect(() => {
    const dishListParam = searchParams.get('dishList');
    const indexParam = searchParams.get('index');
    
    if (dishListParam) {
      try {
        const parsedList = JSON.parse(decodeURIComponent(dishListParam));
        setDishList(parsedList);
        setCurrentIndex(parseInt(indexParam || '0'));
        // 获取菜品列表供编辑使用
        getCookList();
      } catch (error) {
        Toast.show('数据解析失败');
        navigate(-1);
      }
    } else {
      Toast.show('缺少菜品数据');
      navigate(-1);
    }
  }, [searchParams, navigate]);

  // 切换到指定索引
  const switchToDish = (newIndex: number) => {
    if (newIndex < 0 || newIndex >= dishList.length || isTransitioning) {
      return;
    }
    
    setIsTransitioning(true);
    setCurrentIndex(newIndex);
    userSelectedDish.current = false; // 切换菜品时重置用户选择标记
    
    setTimeout(() => {
      setIsTransitioning(false);
    }, 300);
  };

  // 当当前菜品变化时，获取AI识别的菜品名称
  useEffect(() => {
    const currentDish = dishList[currentIndex];
    console.log('当前菜品数据:', currentDish);
    console.log('AI置信度:', currentDish?.aiConfidenceScore);
    console.log('AI预测ID:', currentDish?.aiPredictedDishId);
    
    if (currentDish && currentDish.aiConfidenceScore === 1 && currentDish.aiPredictedDishId) {
      console.log('开始获取AI识别菜品名称...');
      getAiPredictedDishName(currentDish.aiPredictedDishId).then(name => {
        console.log('获取到AI识别名称:', name);
        setAiPredictedDishName(name);
      });
    } else {
      setAiPredictedDishName('');
    }
  }, [currentIndex, dishList]);

  // 单独处理菜品初始化
  useEffect(() => {
    const currentDish = dishList[currentIndex];
    if (currentDish && cookList.length > 0) {
      console.log('初始化菜品选择器 - 当前菜品:', currentDish);
      console.log('菜品列表:', cookList);
      
      // 尝试在cookList中找到匹配的菜品
      const matchedDish = cookList.find(item => 
        item.id === currentDish.id || 
        item.name === currentDish.dishName || 
        item.dishName === currentDish.dishName ||
        item.id === currentDish.dishId // 检查保存的dishId
      );
      
      console.log('匹配的菜品:', matchedDish);
      console.log('当前菜品的dishId:', currentDish.dishId);
      
      // 优先检查是否有保存的dishId
      if (currentDish.dishId && cookList.find(item => item.id === currentDish.dishId)) {
        console.log('找到保存的菜品ID:', currentDish.dishId);
        setSelectedDishId(currentDish.dishId);
        userSelectedDish.current = true; // 标记为已选择
      } else if (matchedDish && 
          currentDish.dishName && 
          !currentDish.dishName.includes('未标注') && 
          currentDish.dishName !== '菜品名称待完善') {
        console.log('根据菜品名称匹配，设置菜品ID:', matchedDish.id);
        setSelectedDishId(matchedDish.id);
      } else if (!userSelectedDish.current) {
        // 只有在用户没有手动选择过的情况下才清空
        console.log('菜品未识别且用户未手动选择，清空选择');
        setSelectedDishId(null);
      } else {
        console.log('保持用户选择的菜品ID:', selectedDishId);
      }
      
      // 更新表单数据
      form.setFieldsValue({
        personEvaluate: [String(currentDish.personEvaluate || 0)],
        tags: currentDish.tags || '',
        wendu: currentDish.dishTemperature || '',
      });
    }
  }, [currentIndex, dishList, cookList, form]);

  // 当selectedDishId变化时，更新表单的dishName字段
  useEffect(() => {
    console.log('selectedDishId 变化:', selectedDishId);
    form.setFieldValue('dishName', selectedDishId ? [selectedDishId] : []);
  }, [selectedDishId, form]);

  // 组件卸载时恢复滚动
  useEffect(() => {
    return () => {
      document.body.style.overflow = '';
    };
  }, []);

  // 处理触摸开始
  const handleTouchStart = (e: React.TouchEvent) => {
    const touch = e.touches[0];
    setTouchStart({ x: touch.clientX, y: touch.clientY });
    setTouchEnd({ x: touch.clientX, y: touch.clientY });
    setIsDragging(true);
  };

  // 处理触摸移动
  const handleTouchMove = (e: React.TouchEvent) => {
    if (!isDragging) return;
    
    const touch = e.touches[0];
    setTouchEnd({ x: touch.clientX, y: touch.clientY });
    
    const deltaX = touch.clientX - touchStart.x;
    const deltaY = Math.abs(touch.clientY - touchStart.y);
    
    // 如果是横向滑动大于纵向滑动，设置拖拽偏移
    if (Math.abs(deltaX) > deltaY) {
      setDragOffset(deltaX);
      // 使用 CSS 来阻止滚动，而不是 preventDefault
      document.body.style.overflow = 'hidden';
    }
  };

  // 处理触摸结束
  const handleTouchEnd = () => {
    if (!isDragging) return;
    
    setIsDragging(false);
    // 恢复页面滚动
    document.body.style.overflow = '';
    
    const deltaX = touchEnd.x - touchStart.x;
    const deltaY = Math.abs(touchEnd.y - touchStart.y);
    
    // 只有横向滑动距离大于纵向滑动距离且大于阈值时才切换
    if (Math.abs(deltaX) > deltaY && Math.abs(deltaX) > 50) {
      if (deltaX > 0) {
        // 右滑 - 上一个菜品
        if (currentIndex > 0) {
          switchToDish(currentIndex - 1);
        } else {
          Toast.show('已经是第一个菜品了');
        }
      } else {
        // 左滑 - 下一个菜品
        if (currentIndex < dishList.length - 1) {
          switchToDish(currentIndex + 1);
        } else {
          Toast.show('已经是最后一个菜品了');
        }
      }
    }
    
    // 重置拖拽偏移
    setDragOffset(0);
  };

  const currentDish = dishList[currentIndex];

  if (!currentDish) {
    return (
      <div className={styles.container}>
        <NavBar onBack={() => navigate(-1)}>菜品详情</NavBar>
        <div className={styles.loading}>加载中...</div>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <NavBar 
        onBack={() => navigate(-1)}
        right={
          <div className={styles.indicator}>
            {currentIndex + 1} / {dishList.length}
          </div>
        }
      >
        菜品详情
      </NavBar>
      
      <div 
        ref={containerRef}
        className={styles.content}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
        style={{
          transform: `translateX(${isDragging ? dragOffset : 0}px)`,
          transition: isDragging ? 'none' : 'transform 0.3s ease-out'
        }}
      >
        <div className={styles.dishCard}>
          {/* 菜品图片 */}
          <div className={styles.imageContainer}>
            <Image
              src={currentDish.dishPicture || ''}
              width="100%"
              height={200}
              fit="cover"
              style={{ borderRadius: '8px' }}
              placeholder={<div className={styles.imagePlaceholder}>暂无图片</div>}
              onClick={() => setShowImageViewer(true)}
            />
          </div>

          {/* 基本信息 */}
          <div className={styles.basicInfo}>
            <div className={styles.infoGrid}>
              <div className={styles.infoItem}>
                <span className={styles.label}>门店：</span>
                <span className={styles.value}>{currentDish.storeName || '-'}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>时间：</span>
                <span className={styles.value}>{currentDish.recordTime || '-'}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>温度：</span>
                <span className={styles.value}>{currentDish.dishTemperature || '-'}°C</span>
              </div>
            </div>
          </div>

          {/* AI区域 */}
          <div className={styles.aiSection}>
            <h3 className={styles.sectionTitle}>AI识别结果</h3>
            
            <div className={styles.aiContent}>
              {/* AI识别菜品名称 */}
              <div className={styles.aiDishName}>
                <span className={styles.label}>识别菜品：</span>
                <span className={styles.value}>
                  {getDishName(currentDish) || '未识别'}
                </span>
              </div>

              {/* AI评价 */}
              {shouldShowAiEvaluation(currentDish) ? (
                <div className={styles.aiEvaluate}>
                  <div className={styles.evaluateInfo}>
                    <span className={styles.label}>AI评价：</span>
                    <span className={styles[getEvaluateStyle(getAiScore(currentDish))]}>
                      {aiTypeEnum[getAiScore(currentDish)] || '待识别'}
                    </span>
                  </div>
                  <Image
                    src={getEvaluateImage(getAiScore(currentDish))}
                    width={40}
                    height={getEvaluateStyle(getAiScore(currentDish)) === 'padd' ? 38 : 33}
                  />
                </div>
              ) : (
                <div className={styles.aiEvaluate}>
                  <div className={styles.evaluateInfo}>
                    <span className={styles.label}>AI评价：</span>
                    <span className={styles.padd}>待识别</span>
                  </div>
                  <Image
                    src={padd}
                    width={40}
                    height={38}
                  />
                </div>
              )}
            </div>
          </div>

          {/* 人工区域 */}
          <div className={styles.manualSection}>
            <h3 className={styles.sectionTitle}>人工评估</h3>
            
            <Form 
              form={form} 
              layout="horizontal" 
              onFinish={handleManualSave}
              className={styles.manualForm}
            >
              {/* 人工菜品名称 */}
              <Form.Item
                name="dishName"
                label="菜品名称"
                className={styles.formItem}
              >
                <Select
                  style={{ width: "100%" }}
                  showSearch
                  optionFilterProp="label"
                  placeholder={(() => {
                    const currentDish = dishList[currentIndex];
                    if (!currentDish?.dishName || 
                        currentDish.dishName.includes('未标注') || 
                        currentDish.dishName === '菜品名称待完善') {
                      return "未识别";
                    }
                    return currentDish.dishName;
                  })()}
                  value={selectedDishId || undefined}
                  onSelect={(value) => {
                    console.log('=== 菜品选择开始 ===');
                    console.log('选择菜品ID:', value);
                    userSelectedDish.current = true; // 标记用户已手动选择
                    setSelectedDishId(value);
                    
                    // 更新当前菜品的dishId（用于保存时提交）
                    const updatedDishList = [...dishList];
                    updatedDishList[currentIndex] = {
                      ...updatedDishList[currentIndex],
                      dishId: value,
                    };
                    setDishList(updatedDishList);
                    
                    // 更新表单值
                    form.setFieldValue('dishName', value);
                    console.log('=== 菜品选择结束 ===');
                  }}
                  options={cookList.map(item => ({
                    label: item.name || item.dishName,
                    value: item.id,
                  }))}
                />
              </Form.Item>

              {/* 人工评分 */}
              <Form.Item
                name="personEvaluate"
                label="菜品分数"
                className={styles.formItem}
                trigger="onConfirm"
                onClick={(e, datePickerRef: any) => {
                  datePickerRef.current?.open();
                }}
              >
                <Picker 
                  columns={scoreOptions}
                  onConfirm={(value) => {
                    console.log('=== 评分选择开始 ===');
                    console.log('选择的值:', value);
                    console.log('当前索引:', currentIndex);
                    console.log('评分前的菜品数据:', dishList[currentIndex]);
                    
                    // 直接更新当前菜品数据
                    const updatedDishList = [...dishList];
                    const newEvaluate = parseInt(String(value[0] || 0));
                    updatedDishList[currentIndex] = {
                      ...updatedDishList[currentIndex],
                      personEvaluate: newEvaluate,
                    };
                    
                    console.log('新的评分值:', newEvaluate);
                    console.log('更新后的菜品数据:', updatedDishList[currentIndex]);
                    
                    setDishList(updatedDishList);
                    
                    // 验证状态是否真的更新了
                    setTimeout(() => {
                      console.log('延迟检查 - 最新的菜品数据:', dishList[currentIndex]);
                    }, 100);
                    
                    console.log('=== 评分选择结束 ===');
                  }}
                >
                  {(val) => {
                    console.log('Picker render - val:', val);
                    return val?.[0] ? val?.[0]?.label : "请选择分数";
                  }}
                </Picker>
              </Form.Item>

              {/* 标签输入 */}
              <Form.Item
                name="tags"
                label="菜品标签"
                className={styles.formItem}
              >
                <div className={styles.tagInputContainer}>
                  <Input 
                    placeholder='请输入菜品标签,标签之间用"#"号隔开'
                    value={dishList[currentIndex]?.tags || ''}
                    onChange={(value) => {
                      console.log('标签输入:', value);
                      console.log('输入前的菜品数据:', dishList[currentIndex]);
                      
                      // 直接更新当前菜品数据
                      const updatedDishList = [...dishList];
                      updatedDishList[currentIndex] = {
                        ...updatedDishList[currentIndex],
                        tags: value,
                      };
                      setDishList(updatedDishList);
                      
                      console.log('输入后的菜品数据:', updatedDishList[currentIndex]);
                    }}
                  />
                  <Button 
                    size="small"
                    className={styles.historyTagsBtn}
                    onClick={getHistoryTags}
                  >
                    <ClockCircleOutline style={{ fontSize: '12px', marginRight: '4px' }} />
                    历史标签
                  </Button>
                </div>
              </Form.Item>

              {/* 保存按钮 */}
              {JSON.parse(localStorage.getItem("info") || "{}")?.permission?.includes("0") ? (
                <div className={styles.saveButtonContainer}>
                  <Button
                    color="primary"
                    size="large"
                    className={styles.saveButton}
                    onClick={() => form.submit()}
                  >
                    保存评估
                  </Button>
                </div>
              ) : (
                <div className={styles.noPermissionHint}>
                  您没有评估权限，只能查看菜品信息
                </div>
              )}
            </Form>
          </div>

          {/* 滑动提示 */}
          <div className={styles.swipeHint}>
            左滑查看下一个，右滑查看上一个
          </div>
        </div>
      </div>

      {/* 图片查看器 */}
      <ImageViewer
        image={currentDish?.dishPicture || ''}
        visible={showImageViewer}
        onClose={() => setShowImageViewer(false)}
      />

      {/* 历史标签弹窗 */}
      {showHistoryTags && (
        <div className={styles.historyTagsModal}>
          <div className={styles.historyTagsContent}>
            <div className={styles.historyTagsHeader}>
              <span>历史标签</span>
              <Button 
                size="small" 
                fill="none"
                onClick={() => setShowHistoryTags(false)}
              >
                关闭
              </Button>
            </div>
            <div className={styles.historyTagsList}>
              {historyTags.length > 0 ? (
                historyTags.map((tag, index) => (
                  <div 
                    key={index} 
                    className={styles.historyTag}
                    onClick={() => addHistoryTag(tag)}
                  >
                    {tag}
                  </div>
                ))
              ) : (
                <div className={styles.noHistoryTags}>暂无历史标签</div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default DishViewer;